package com.yazif.vqa.dao.impl;

import com.alibaba.fastjson.JSON;
import com.yazif.vqa.dao.RedisDao;
import com.yazif.vqa.domain.Deal;
import com.yazif.vqa.domain.Pend;
import com.yazif.vqa.util.Redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

@Repository
@PropertySource("classpath:application.properties")
public class RedisImpl implements RedisDao {

    @Autowired
    Redis redis;

    @Value("${spring.wechat.image.timeout}")
    int imageTimeout;

    @Override
    public void set(String key, String value) {
        set(key, imageTimeout, value);
    }

    @Override
    public void set(String key, int timeout, String value) {
        Jedis jedis = null;
        try {
            jedis = redis.getJedis();
            jedis.setex(key, timeout, value);
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }

    @Override
    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = redis.getJedis();
            return jedis.get(key);
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }

    @Override
    public void lpush(String key, Pend pend) {
        Jedis jedis = null;
        try {
            jedis = redis.getJedis();
            String pendString = JSON.toJSONString(pend);
            jedis.lpush(key, pendString);
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }

    @Override
    public Deal brPop(String key) {

        Jedis jedis = null;
        Deal deal = null;
        try {
            jedis = redis.getJedis();
            List<String> value = jedis.brpop(0, key);

            for (String v : value){
                if (key.equals(v)){
                    continue;
                }
                v = v.replace("u\'", "\"");
                v = v.replace("'", "\"");
                deal = JSON.parseObject(v, Deal.class);
            }
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return deal;
    }


}
